package util.file;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LineFilter {
	
	String former = "IP";
	String latter = "Name";
	String line;
	String ip;
	String name;
	
	/*
	 * 匹配空行的正则表达式
	 */
	
	String spaceRegex = "\\s*(\\n||\\r)$";
	Pattern spacePattern;
	Matcher spaceMatcher;
	
	/*
	 * 匹配ip地址的正则表达式
	 */
	String ipRegex = "^([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){3}$";
	Pattern ipPattern;
	Matcher ipMatcher;
	
	
	public LineFilter() {
		spacePattern = Pattern.compile(spaceRegex);
		ipPattern = Pattern.compile(ipRegex);
	}
	
	public void setLine(String line) {
		this.line = line;
	}
	
	public boolean isUseless() {
		return isEndWith() || isSpaceLine() || isStartWith();
	}
	
	/*
	 * filter line useless
	 */
	public boolean isEndWith() {
		String suffix = "local";
		return line.endsWith(suffix);
	}

	
	public boolean isSpaceLine() {
		spaceMatcher = spacePattern.matcher(line);
		boolean isSpace = spaceMatcher.matches();
		return isSpace;
	}
	
	public boolean isStartWith() {
		String prefix = "#";
		return line.startsWith(prefix);
	}
	
	
	/*
	 * filter ipv4
	 */

	
	public boolean isIp() {
		ipMatcher = ipPattern.matcher(name);
		return ipMatcher.matches();
	}
	
	
	
	public String ipAndAddr() {
		String[] arp =	getArpArray();
		return arp[0] + "," + arp[1];
	}
	
	public String[] getArpArray() {

		String[] arp = new String[2];
		int commaIndex;
		int ipIndex;
		int nameIndex;	
		ipIndex = line.indexOf(former);
		nameIndex = line.indexOf(latter);
		commaIndex = line.indexOf(",");
		ip = line.substring(ipIndex + 4,commaIndex);
		name = line.substring(nameIndex + 6);
		arp[0] = ip;
		arp[1] = name;
		return arp;
	}
	
	public String ipAndAddr1() {
		
		String[] arp = getArpArray1();
		
		return arp[0] + "," + arp[1];
		
	}
	
	
	public String[] getArpArray1() {
		String[] arp = null;
		String regex = "\\s";
		arp = line.split(regex);
		ip = arp[0];
		name = arp[1];
		return arp;
	}
	
	public boolean isExist() {
		boolean e = line.contains(former) &&
					line.contains(latter);
		return e;
	}

	
	public boolean resolved(String[] ia) {
		ipMatcher = ipPattern.matcher(ia[1]);
		return ipMatcher.matches();
	}

}












